﻿using NCP.Core.DataUtil;
using NCP.Core.IoC;
using NCP.Model;
using SqlSugar;
using System.Collections.Generic;

namespace NCP.Service
{
    public class PermissionService : BaseService<Permission>, IService
    {
        public PermissionService()
        {
            _client = DbHelper.GetSqlSugarClient();
        }

        //获取目录，菜单
        public List<Permission> GetsPms()
        {
            return _client.Queryable<Permission>()
                .Where(p => p.PmsType.ToLower() != "p")
                .OrderBy(p => p.Id)
                .OrderBy(p => p.Sort)
                .ToList();
        }

        public List<Permission> GetPmsByUserCode(string userCode, bool issysadmin)
        {
            List<Permission> pList = _client.Ado
                .SqlQuery<Permission>(@"select distinct s.* from MemberInRole u inner join pmsinrole p on u.roleid=p.roleid
                inner join permission s on p.pmsid=s.id
                where u.Code=@StaffCode order by s.Sort", new SugarParameter("@StaffCode", userCode));
            if (pList == null || pList.Count == 0)
            {
                pList = _client.Ado
                    .SqlQuery<Permission>(@"select distinct s.* from pmsinrole p inner join permission s on p.pmsid=s.id
                    inner join role r on p.roleid=r.id and r.isdefault='Y' order by s.Sort");
            }

            if (issysadmin)
            {
                pList = _client.Queryable<Permission>().ToList();
            }
            List<Permission> currentPmsList = new List<Permission>();

            currentPmsList.AddRange(pList.FindAll(t => t.PmsType.ToLower() == "m"));
            currentPmsList.ForEach(c => {
                c.SubPermissionList = pList.FindAll(t => t.ParentId == c.Id);
                if (c.SubPermissionList != null)
                {
                    c.SubPermissionList.ForEach(s => s.SubPermissionList = pList.FindAll(t => t.ParentId == s.Id));
                }
            });

            return currentPmsList;
        }
    }
}
